// #region ********** 变量 **********

var filterList = []; // 层级孪生体对象列表
var filterSettingData = null; // 过滤设置数据
var currentFilterId = null; // 当前左侧面板点击的过滤Id

// #endregion ********** 变量 **********

// #region ********** TwinIOC 初始化阶段 **********

// 创建并获取场景实例对象
function init() {
  window.tgTwinIOC = new twinIOC();
  let { url, locationId, token } = twiniocConfig;

  // 初始化地点
  tgTwinIOC.initLocation({ locationId, url, token }, (result) => {
    // console.log(result, '初始化地点接口');
  });

  // 注册地点加载完成时间
  tgTwinIOC.uniCall(
    'addEventListener',
    {
      eventName: 'locationInit',
      callback: () => {
        // 显示左侧面板
        document.querySelector('.left-panel-container').style.display = 'block';

        // 获取层级孪生体对象列表
        getFilterList();
      },
    },
    (result) => {}
  );
}

// #endregion ********** TwinIOC 初始化阶段 **********

// #region ********** TwinIOC 相关操作 **********

// 获取过滤器列表
function getFilterList() {
  tgTwinIOC.uniCall('getFilterList', {}, (result) => {

    filterList = result.data;
    renderFilterList();
  });
}

// 获取过滤参数
function getFilterParams(filterId) {
  let jsonData = {
    filterId: filterId,
  };

  tgTwinIOC.uniCall('getFilterSetting', jsonData, (result) => {
    // console.log(result);
    filterSettingData = result;

    // 设置右侧面板标题
    document.querySelector('.right-panel-container .title-name').innerHTML = filterSettingData.filterName;

    // 渲染右侧过滤列表数据
    renderRightPanelFilterSetting();

    currentFilterId = filterId;
  });
}

/**
 * 过滤器列表项点击事件 设置过滤条件
 *
 * @param {string} conditionId - 过滤条件 Id
 */
function onFilterSettingCheckClick(conditionId) {
  // 获取当前过滤条件
  let conditionsDom = document.querySelectorAll(`#condition-${conditionId} input`);
  let valueList = [];
  conditionsDom.forEach((item) => {
    if (item.checked) {
      // 从类名ID中获取选择的标签文本
      valueList.push(item.id);
    }
  });

  let conditionsData = [
    {
      conditionId: conditionId,
      value: valueList,
    },
  ];

  setFilterSetting(currentFilterId, conditionsData);
}

/**
 * 获取设置过滤参数
 *
 * @param {string} filterId - 过滤 Id
 * @param {Array} conditions - 过滤条件数据
 */
function setFilterSetting(filterId, conditions) {
  let jsonData = {
    filterId: filterId,
    conditions: conditions,
  };

  tgTwinIOC.uniCall('setFilterSetting', jsonData, (result) => {
    // console.log(result);
  });
}

// 重置过滤设置
function resetFilterSetting() {
  // 重置过滤数据
  let conditionsData = filterSettingData.conditions.map((item) => {
    if (item.fieldType == '数值' || item.fieldType == 'Decimal' || item.fieldType == 'Int') {
      return {
        conditionId: item.conditionId,
        value: [Number(item.valueRange[0]), Number(item.valueRange[1])],
      };
    } else if (item.fieldType == '字符串') {
      return {
        conditionId: item.conditionId,
        value: item.valueRange.filter((value) => value.select).map((value) => value.label),
      };
    } else {
      return {
        conditionId: item.conditionId,
        value: [],
      };
    }
  });
  setFilterSetting(currentFilterId, conditionsData);

  // 重新渲染过滤设置列表
  renderRightPanelFilterSetting();
}

/**
 * 点击过滤器列表项
 *
 * @param {Element} dom - 当前过滤列表项的 DOM 元素
 * @param {string} filterId - 过滤 Ids
 */
function onFilterItemClick(dom, filterId) {
  // 对象列表项的选中高亮状态
  document.querySelectorAll('.left-panel-container .filter .list-group-item').forEach((item) => {
    item.classList.remove('active');
  });

  dom.classList.add('active');
  getFilterParams(filterId);

  // 显示右侧面板
  document.querySelector('.right-panel-container').style.display = 'block';
}

// #endregion ********** TwinIOC 相关操作 **********

// #region ********** HTML界面控件的事件处理函数 **********

// 渲染过滤列表
function renderFilterList() {
  let filterListDom = document.querySelector('.left-panel.filter');
  let filterListStr = '';

  filterList.forEach((item, index) => {
    let filterItemStr = '';
    if (item.filters && item.filters.length) {
      item.filters.forEach((filterItem) => {
        filterItemStr += `<li class="list-group-item" onclick="onFilterItemClick(this, '${filterItem.filterId}')">${filterItem.filterName}</li>`;
      });
    }

    filterListStr += `<div class="accordion-item">
    <h2 class="accordion-header" id="heading${index}">
      <button
        class="accordion-button"
        type="button"
        data-bs-toggle="collapse"
        data-bs-target="#collapse${index}"
        aria-expanded="true"
        aria-controls="collapse${index}"
      >
        <span>${item.folderName}</span>
        <div class="accordion-header-right">
          <span class="icon-arrow">></span>
        </div>
      </button>
    </h2>
    <div id="collapse${index}" class="accordion-collapse collapse show" aria-labelledby="heading${index}">
      <div class="accordion-body">
        <ul class="list-group">
          ${filterItemStr}
        </ul>
      </div>
    </div>
  </div>`;
  });

  filterListDom.innerHTML = filterListStr;
}

// 渲染右侧过滤列表数据
function renderRightPanelFilterSetting() {
  let filterSettingDom = document.querySelector('.right-panel-container .right-panel.filter-setting');
  let filterSettingStr = '';

  filterSettingData.conditions.forEach((item, index) => {
    let conditionStr = '';
    // 文档中的返回值为 数值，实际获取 Decimal
    if (item.fieldType == '数值' || item.fieldType == 'Decimal' || item.fieldType == 'Int') {
      conditionStr = `<div class="range-container">
        <div class="range-slider">
          <div class="slider-track" id="slider-track-${item.conditionId}"></div>
          <div class="slider-thumb min" id="range-min-${item.conditionId}" data-value="${item.valueRange[0]}" 
            onmousedown="startDragging(event, '${item.conditionId}', 'min')"></div>
          <div class="slider-thumb max" id="range-max-${item.conditionId}" data-value="${item.valueRange[1]}"
            onmousedown="startDragging(event, '${item.conditionId}', 'max')"></div>
        </div>
        <div class="range-values">
          <span id="min-value-${item.conditionId}">${item.valueRange[0]}</span>
          <span id="max-value-${item.conditionId}">${item.valueRange[1]}</span>
        </div>
      </div>`;
    } else if (item.fieldType == '字符串' && !item.isSingle) {
      // 多选
      conditionStr += `<div class="box-container" id="condition-${item.conditionId}">`;
      item.valueRange.forEach((value) => {
        conditionStr += `<div class="form-check me-3">
          <input type="checkbox" class="form-check-input" id="${value.label}" onclick="onFilterSettingCheckClick('${item.conditionId}')" ${
          value.select ? 'checked' : ''
        }>
          <label class="form-check-label" for="${value.label}">${value.label}</label>
        </div>`;
      });
      conditionStr += `</div>`;
    } else if (item.fieldType == '字符串' && item.isSingle) {
      // 单选
      conditionStr += `<div class="box-container" id="condition-${item.conditionId}">`;
      item.valueRange.forEach((value) => {
        conditionStr += `<div class="form-check me-3">
          <input type="radio" class="form-check-input" name="radio-${item.conditionId}" id="${value.label}" onclick="onFilterSettingCheckClick('${
          item.conditionId
        }')" ${value.select ? 'checked' : ''}>
          <label class="form-check-label" for="${value.label}">${value.label}</label>
        </div>`;
      });
      conditionStr += `</div>`;
    }

    filterSettingStr += `<div class="accordion-item">
    <h2 class="accordion-header">
      <button
        class="accordion-button"
        type="button"
        data-bs-toggle="collapse"
        data-bs-target="#collapse${index}-right"
        aria-expanded="true"
        aria-controls="collapse${index}-right"
      >
        <span>${item.name}</span>

        <div class="accordion-header-right">
          <span class="icon-arrow">></span>
        </div>
      </button>
    </h2>
    <div id="collapse${index}-right" class="accordion-collapse collapse show">
      <div class="accordion-body">
        ${conditionStr}
      </div>
    </div>
  </div>`;
  });

  filterSettingDom.innerHTML = filterSettingStr;
}

// 关闭右侧面板
function closeRightPanelContainer() {
  document.querySelector('.right-panel-container').style.display = 'none';
}

// 拖动滑块相关操作 start
let isDragging = false;
let currentSlider = null;
let currentConditionId = null;
let sliderType = null;

function startDragging(event, id, type) {
  isDragging = true;
  currentSlider = event.target;
  currentConditionId = id;
  sliderType = type;
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDragging);
}

function stopDragging() {
  isDragging = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDragging);

  // 获取滑块的值 设置过滤条件
  let minValue = document.getElementById('min-value-' + currentConditionId).textContent;
  let maxValue = document.getElementById('max-value-' + currentConditionId).textContent;

  let conditionsData = [
    {
      conditionId: currentConditionId,
      value: [Number(minValue), Number(maxValue)],
    },
  ];

  setFilterSetting(currentFilterId, conditionsData);
}

function onDrag(event) {
  if (!isDragging) return;

  const track = currentSlider.parentElement;
  const trackRect = track.getBoundingClientRect();
  let percentage = ((event.clientX - trackRect.left) / trackRect.width) * 100;
  percentage = Math.min(Math.max(percentage, 0), 100);

  const minSlider = document.getElementById('range-min-' + currentConditionId);
  const maxSlider = document.getElementById('range-max-' + currentConditionId);
  const minValue = document.getElementById('min-value-' + currentConditionId);
  const maxValue = document.getElementById('max-value-' + currentConditionId);

  // 获取传入的最小值和最大值
  const minRange = parseFloat(minSlider.getAttribute('data-value')) || 0;
  const maxRange = parseFloat(maxSlider.getAttribute('data-value')) || 100;

  // 拖动时设置滑块位置
  if (sliderType === 'min') {
    const maxPercentage = parseFloat(maxSlider.style.left || 100);
    if (percentage < maxPercentage) {
      currentSlider.style.left = percentage + '%';
      minValue.textContent = Math.round((percentage / 100) * (maxRange - minRange) + minRange);
    }
  } else {
    const minPercentage = parseFloat(minSlider.style.left || 0);
    if (percentage > minPercentage) {
      currentSlider.style.left = percentage + '%';
      maxValue.textContent = Math.round((percentage / 100) * (maxRange - minRange) + minRange);
    }
  }
}
// 拖动滑块相关操作 end

// #endregion ********** HTML界面控件的事件处理函数 **********

window.onload = function () {
  // 初始化
  // 1. 初始化孪易场景
  init();
};
